package view2.utils;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

public class MessagePassengerService extends Service {

    private LocalBroadcastManager localBroadcastManager;
    private BroadcastReceiver localReceiver;

    @Override
    public void onCreate() {
        super.onCreate();
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localReceiver = new LocalReceiver();
        IntentFilter filter = new IntentFilter("com.goods.updata");
        localBroadcastManager.registerReceiver(localReceiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 这里可以执行一些初始化操作
        Log.i("PassengerService", "Service is starting.");
        return START_STICKY; // 可以根据需要选择适当的返回值
    }

    @Override
    public IBinder onBind(Intent intent) {
        // 服务不需要绑定到活动，返回null
        return null;
    }

    private class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("PassengerService", "Received broadcast in service.");
            // 执行一些操作，比如更新数据
            // ...
            // 发送一个本地广播到TestActivity，通知它服务已经处理了消息
            Intent localIntent = new Intent("com.goods.processed");
            localBroadcastManager.sendBroadcast(localIntent);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localReceiver);
        Log.i("PassengerService", "Service is stopping.");
    }
}